<script setup>
import { ref, toRefs, onMounted, onUnmounted, computed, nextTick } from 'vue'
defineOptions({
  name: 'DeletePopover'
})

// 设置显示和隐藏
const modelValue=defineModel({type:Boolean})
const props = defineProps({
  placement: { // 位置
    type:String,
    default:'left'
  },
  tempRef: {
    type: Object,
    default: () => ({})
  },
  delInfo: {
    type: Object,
    default: () => ({
      id: Number,
      title: String
    })
  }
})
const { delInfo } = toRefs(props)
const emit = defineEmits(['update:delInfo', 'on-submit'])
const delPop = ref()
const cancelDel = () => {
  const _obj = {
    id: undefined,
    title: ''
  }
  emit('update:delInfo', _obj)
  emit('update:modelValue', false)
}
const isSubmit = ref(false)
const submit = () => {
  isSubmit.value = true
  emit('on-submit')
  cancelDel()
}

const visible = computed({
  get: () => modelValue.value,
  set: (val) => {
    emit('update:modelValue', val)
  }
})

const handleBlur = async () => {
  // addEventListener('blur') 执行比按钮事件快,因此需要加个延时
  setTimeout(() => {
    if (!isSubmit.value) {
      cancelDel()
    }
  }, 200)
}
let _popover

onMounted(async() => {
  // 点击空白处 关闭浮窗pop
  _popover = document.querySelector('.delete-popper')
  await nextTick()
  _popover.focus()
  _popover.addEventListener('blur', handleBlur)
  document.querySelector('.table-view__body .el-scrollbar__wrap').addEventListener('scroll', cancelDel)
})
onUnmounted(() => {
  if (!isSubmit.value) isSubmit.value = false
  if (delPop.value) delPop.value = false
  document.querySelector('.table-view__body .el-scrollbar__wrap').removeEventListener('scroll', cancelDel)
  _popover.removeEventListener('blur', handleBlur)
})
</script>
<template>
  <ElPopover
      ref="delPop"
      popper-class="delete-popper"
      :placement="placement"
      :visible="visible"
      :virtual-ref="props.tempRef"
      virtual-triggering
      trigger="click"
      width="200px"
  >
    <div class="del-icon">
      <ElIcon>
        <Delete/>
      </ElIcon>
    </div>
    <p class="mb-1">确定要删除这条<b style="color:var(--el-color-danger);">{{ delInfo.title }}</b>数据吗？</p>
    <div class="popover-footer">
      <ElButton link @click="cancelDel">取消</ElButton>
      <ElButton type="danger" @click.prevent="submit">确定</ElButton>
    </div>
  </ElPopover>
</template>

<style lang="scss">
.delete-popper {
  width: 200px !important;

  .del-icon {
    @include text-align;
    padding: 0 10px 10px;

    .el-icon {
      display: inline-block;
      width: 48px;
      height: 48px;
      line-height: 52px;
      text-align: center;
      font-size: 24px;
      border-radius: 24px;
      background-color: var(--el-color-danger);
      color: #fff;
    }
  }

  .popover-footer {
     text-align:center;
  }
}
</style>
